package cloud.xlh.my_system.config;

import cloud.xlh.infrastructure.enums.DataSourceEnum;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/3/26 11:48
 * @ Description:
 */
public class DynamicDataSourceContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return DataSourceEnum.MASTER.getDesc();
        }
    };

    private static List<Object> dataSourceKeys = new ArrayList<Object>();

    public static void setDataSourceKeys(String key) {
        contextHolder.set(key);
    }

    public static String getDataSourceKey() {
        return contextHolder.get();
    }

    public static void clearDataSourceKey() {
        contextHolder.remove();
    }

    public static boolean containDataSourceKey(String key) {
        return dataSourceKeys.contains(key);
    }

    // 切换数据源
    public static void switchDataSourceKey() {
        String currentKey = getDataSourceKey();
        for (Object dataSourceKey : dataSourceKeys) {
            if (!dataSourceKey.equals(currentKey)) {
                setDataSourceKeys((String) dataSourceKey);
                return;
            }
        }
    }
}
